#!/bin/bash
set -e

# version check: https://github.com/ImageMagick/ImageMagick/releases
IMAGE_MAGICK_VERSION="7.1.2-3"
IMAGE_MAGICK_HASH="b16415e8694a2e15e5282d64fc7b358f309ff3a514a90eb5da268676c772de3d"

LIBJPEGTURBO=$(cat /etc/issue | grep -qi Debian && echo 'libjpeg62-turbo libjpeg62-turbo-dev' || echo 'libjpeg-turbo8 libjpeg-turbo8-dev')

PREFIX=/usr/local
WDIR=/tmp/imagemagick

# Install build deps
apt -y -q remove imagemagick
apt -y -q install git make gcc pkg-config autoconf curl g++ yasm cmake \
    libde265-0 libde265-dev ${LIBJPEGTURBO} libwebp7 x265 libx265-dev libtool \
    libpng16-16 libpng-dev libwebp-dev libgomp1 libaom-dev \
    libwebpmux3 libwebpdemux2 ghostscript libxml2-dev libxml2-utils librsvg2-dev \
    libltdl7-dev libbz2-dev gsfonts libtiff-dev libfreetype6-dev libjpeg-dev

if cat /etc/issue | grep -qi Debian; then
  # Get VERSION_CODENAME
  . /etc/os-release
  # Use backports
  apt -y -q install libheif1/$VERSION_CODENAME-backports libheif-dev/$VERSION_CODENAME-backports
else
  apt -y -q install libheif1 libheif-dev
fi

mkdir -p $WDIR
cd $WDIR

# Build and install ImageMagick
wget -q -O $WDIR/ImageMagick.tar.gz "https://github.com/ImageMagick/ImageMagick/archive/$IMAGE_MAGICK_VERSION.tar.gz"
sha256sum $WDIR/ImageMagick.tar.gz
echo "$IMAGE_MAGICK_HASH $WDIR/ImageMagick.tar.gz" | sha256sum -c
IMDIR=$WDIR/$(tar tzf $WDIR/ImageMagick.tar.gz --wildcards "ImageMagick-*/configure" |cut -d/ -f1)
tar zxf $WDIR/ImageMagick.tar.gz -C $WDIR
cd $IMDIR
PKG_CONF_LIBDIR=$PREFIX/lib LDFLAGS=-L$PREFIX/lib CFLAGS='-O2 -I$PREFIX/include' ./configure \
          --prefix=$PREFIX \
          --disable-shared \
          --enable-delegate-build \
          --enable-static \
          --enable-bounds-checking \
          --enable-hdri \
          --enable-hugepages \
          --with-threads \
          --with-modules \
          --with-quantum-depth=16 \
          --without-magick-plus-plus \
          --with-bzlib \
          --with-zlib \
          --without-autotrace \
          --with-freetype \
          --with-jpeg \
          --without-lcms \
          --with-lzma \
          --with-png \
          --with-tiff \
          --with-heic \
          --with-rsvg \
          --with-webp
make all -j"$(nproc)" && make install

cd $HOME
rm -rf $WDIR
ldconfig /usr/local/lib

# Validate ImageMagick install
test $(magick -version | grep -o -e png -e tiff -e jpeg -e freetype -e heic -e webp | wc -l) -eq 6
